package com.ykt.controller;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.ykt.common.constant.ParamNames;
import com.ykt.common.utils.Colls;
import com.ykt.common.utils.DateUtil;
import com.ykt.common.utils.ModelUtil;
import com.ykt.common.utils.UB;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.converter.MediaSourceConverter;
import com.ykt.converter.ShopConverter;
import com.ykt.model.MediaSource;
import com.ykt.model.Order;
import com.ykt.model.Shop;
import com.ykt.model.User;
import com.ykt.service.MediaSourceService;
import com.ykt.service.OrderService;
import com.ykt.service.ShopService;
import com.ykt.service.UserService;
import com.ykt.validator.CommonValidator;
import com.ykt.validator.ShopValidator;
import com.ykt.vo.MediaSourceVo;
import com.ykt.vo.OrderVo;
import com.ykt.vo.ResultStatus;
import com.ykt.vo.ResultVo;
import com.ykt.vo.ShopVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商铺API
 *
 * @author long.hua
 * @version 1.0.0
 * @since 2016-01-17 14:07
 */
public class ShopController extends BaseController {
    private final static Logger LOGGER = LoggerFactory.getLogger(ShopController.class);

    private ShopService shopService = enhance(ShopService.class.getName(), ShopService.class);
    private OrderService orderService = enhance(OrderService.class.getName(), OrderService.class);
    private MediaSourceService mediaSourceService = enhance(MediaSourceService.class.getName(), MediaSourceService.class);
    private UserService userService = enhance(UserService.class.getName(), UserService.class);

    //商户查询
    @Before({CommonValidator.UserIdValidator.class, CommonValidator.MarketIdValidator.class, ShopValidator.class})
    public void find() {
        Integer userId = UB.i(getParaToInt(ParamNames.userId), -1);
        Integer marketId = UB.i(getParaToInt(ParamNames.marketId), -1);
        Integer categoryId = UB.i(getParaToInt(ParamNames.categoryId), -1);
        String shopName = getPara(ParamNames.shopName);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(ParamNames.marketId, marketId);
        paramMap.put(ParamNames.categoryId, categoryId);
        paramMap.put(ParamNames.userId, userId);
        paramMap.put(ParamNames.name, shopName);
        PageParam<Map<String, Object>> param = super.toPageParam(paramMap);

        PageData<Shop> pd = shopService.paginate(param);
        if (pd == null || pd.getPageData() == null) {
            this.returnJson(ResultVo.success(pd));
        } else {
            List<ShopVo> shopVos = ShopConverter.convert(pd.getPageData());
            this.returnJson(ResultVo.success(pd.convert(shopVos)));
        }
    }

    //商户查询订单
    @Before(CommonValidator.ShopIdValidator.class)
    public void historyOrder() {
        int shopId = UB.i(getPara("shopId"));

        PageParam<Integer> param = this.toPageParam(shopId);
        PageData<Order> pd = orderService.paginateByShopId(param);
        if(pd == null){

            this.returnJson(ResultVo.failure(null, ResultStatus.SELECT_FAILURE_MSG));

        } else if(Colls.isEmpty(pd.getPageData())){

            this.returnJson(ResultVo.success(null));

        } else {

            PageData<OrderVo> voPd = pd.convert(new ArrayList<OrderVo>());

            for (Order order : pd.getPageData()) {
                String phone = order.getStr(ParamNames.userName);
                if (StrKit.isBlank(phone)) {
                    continue;
                }
                phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
                Date createdTime = order.getDate(Order.created_time);

                OrderVo vo = new OrderVo();
                vo.setUserName(phone);// 使用用户手机代替用户名
                vo.setCreatedTime(DateUtil.ymdhms2(createdTime));
                vo.setAmount(ModelUtil.d(order, Order.amount));

                voPd.getPageData().add(vo);
            }

            this.returnJson(ResultVo.success(voPd));
        }
    }

    public void recommend() {
        int userId = UB.i(getPara("userId"));
        int marketId = UB.i(getPara("marketId"));

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(ParamNames.marketId, marketId);
        queryMap.put(ParamNames.userId, userId);
        queryMap.put(Shop.recommend, 1);
        PageParam<Map<String, Object>> param = new PageParam<>(0, 30, queryMap);

        PageData<Shop> shops = shopService.paginate(param);
        if (shops == null || Colls.isEmpty(shops.getPageData())) {
            this.returnJson(ResultVo.success(shops));

        } else {
            List<ShopVo> shopVos = ShopConverter.convert(shops.getPageData());
            this.returnJson(ResultVo.success(shops.convert(shopVos)));
        }
    }

    public void detail() {
        int userId = UB.i(getPara("userId"));
        int shopId = UB.i(getPara("shopId"));

        Shop shop = shopService.findById(shopId);
        
        ShopVo shopVo = ShopConverter.convert(shop);
        
        User merchant = userService.find(shop.getInt(Shop.merchant_id));
        shopVo.setMerchantHead(merchant.getStr(User.head));
        shopVo.setMerchantName(merchant.getStr(User.name));
        shopVo.setMerchantPhone(merchant.getStr(User.phone));

        this.setMediaSources(Arrays.asList(shopVo));

        this.returnJson(ResultVo.success(shopVo));
    }

    private void setMediaSources(List<ShopVo> vos) {
        List<Integer> bizIds = new ArrayList<>();
        for (ShopVo vo : vos) {
            bizIds.add(vo.getId());
        }

        Map<String, List<MediaSource>> mediaSourceMap = mediaSourceService.find(MediaSource.BizType.SHOP, bizIds);
        if (mediaSourceMap == null) {
            return;
        }

        for (ShopVo marketVo : vos) {
            String key = MediaSource.BizType.SHOP.name() + marketVo.getId();
            List<MediaSource> mediaSources = mediaSourceMap.get(key);

            List<MediaSourceVo> mediaSourceVos = MediaSourceConverter.convert(mediaSources);
            marketVo.setMediaSources(mediaSourceVos);
        }
    }
}
